const mongoose = require("mongoose");
var Product = mongoose.model("product");
var Ristory = mongoose.model("ristory");

exports.addProduct = function(req,res){
	Ristory.findOne({_id:req.body.rid},function (err,ristory) {
		if(!err){
			var product = new Product();
			product.pname = req.body.pname;
			product.price = req.body.price;
			product.num = req.body.num;
			product.ristory = ristory;
			product.save(function(err){
				if(!err){
					res.json(product);
				}else{
					res.json({error: "can't add product"});
				}
			})
		}else{
			res.json({error: "can't find ristory to add product"});
		}
	})
}

exports.deleteProduct = function(req,res){
	Product.findOne({_id:req.params.id},function(err,product){
		if(!err){
			product.remove(function(err){
				if(!err){
					res.json({});
				}else{
					res.json({error: "can't remove product by id = " + req.params.id});
				}
			})
		}else{
			res.json({error: "can't find product"});
		}
	})
}

exports.updateProduct = function(req,res){
	Product.findByIdAndUpdate(req.params.id,req.body,function(err,oldProduct){
		if(!err){
			Product.findOne({_id:req.params.id},function(err,product){
				if(!err){
					res.json(product);	
				}else{
					res.json({error:"can't update product by id = " + req.params.id});
				}
			})
		}else{
			res.json({error:"can't update product by id = " + req.params.id});
		}
	})
}

exports.getProducts = function(req,res){
	if(req.query.rid!= undefined){
		Product.find({ristory:mongoose.Types.ObjectId(req.query.rid)},function(err,products){
			if(!err){
				res.json(products);
			}else{
				res.json({error: "can't find products by ristory id = " + req.query.rid});
			}
		})
	}else{
		Product.find(function(err,products){
			if(!err){
				res.json(products)
			}else{
				res.json({error: "can't find all products"});
			}
		})
	}
}
